package development.bussiness;

import java.util.Vector;

import state.socket.DataPackage;
import state.util.Hashtable;
import development.Global;
import development.bean.Subscription;

public class SubscriptionBussiness {

  public void onReceiveSubscription(DataPackage dataPackage) {
    Hashtable subs = (Hashtable) Global.subscriptionMap.get(Global.currentUser.getName());
    if (subs == null) {
      subs = new Hashtable();
    }

    Subscription sub = new Subscription();
    sub.id = dataPackage.nextInt();
    sub.subcriber = dataPackage.nextString();
    sub.operator = dataPackage.nextString();
    sub.service = dataPackage.nextString();
    sub.request = dataPackage.nextString();
    sub.startTime = dataPackage.nextString();
    sub.endTime = dataPackage.nextString();
    sub.status = dataPackage.nextInt();
    sub.providerId = dataPackage.nextInt();

    Vector subService = (Vector) subs.get(sub.service);
    if (subService == null) {
      subService = new Vector();
    }
    if (subService.isEmpty()) {
      subService.addElement(sub);
    }
    if(!isHasSubscription(subService, sub)){
      subService.addElement(sub);
    }
    subs.put(sub.service, subService);
    Global.subscriptionMap.put(Global.currentUser.getName(), subs);
  }
  
  private boolean isHasSubscription(Vector subService, Subscription newSub){
    for(int i = 0; i < subService.size(); i++){
      Subscription currSubscription = (Subscription) subService.elementAt(i);
      if(currSubscription.request.equals(newSub.request)){
        return true;
      }
    }
    return false;
  }
}
